﻿package extremefx.collections {
	import extremefx.IEnumerator;	
	
	/**
	 * @author Marcelo Volmaro
	 */
	internal final class TPreEnum implements IEnumerator {
		private var _root:TreeNode;
		private var _node:TreeNode;
		private var _mode:Function;
		
		public function TPreEnum(pHead:TreeNode) {
			_root = pHead;
			reset();
		}
	
		public function moveNext():Boolean {
			var tmpNode:TreeNode;
			if (_node){
				if ((tmpNode = _node._first)){//if tree has at least one child
					_node = tmpNode;
					
				} else {//node is childless, move to next sibling
					if (_node == _root){
						_node = null;
					
					} else if ((tmpNode = _node._next)){//node has a sibling node
						_node = tmpNode;
						
					} else {//node has no sibling, move to parent next sibling
						tmpNode = _node;
						
						while(true){
							if (tmpNode == _root){
								tmpNode = null;
								break;
								
							} else if (tmpNode._next){
								tmpNode = tmpNode._next;
								break;
								
							} else {
								tmpNode = tmpNode._parent;
							}
						}
						
						_node = tmpNode;
					}
				}
				
			} else {
				_node = _root;
			}
			
			return _node != null;
		}
		
		public function reset():void {
			_node = null;
		}
		
		public function get current():* {
			return _node;
		}
	}
}
